import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'

// 创建axios实例
const service: AxiosInstance = axios.create({
    baseURL: 'http://cylyxsz.w1.luyouxia.net/blog/api',
    timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 在请求发送之前做一些处理
        const token = localStorage.getItem('token')
        if (token && config.headers) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    (error: any) => {
        return Promise.reject(error)
    }
)

// 修改响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse<any>) => {
        const res = response.data
        if (res.code === 200 || res.code === '0') {
            // 如果是列表接口，需要返回完整的数据结构
            if (res.data && (res.data.list !== undefined)) {
                return {
                    list: res.data.list.map((item: any) => ({
                        ...item,
                        replies: item.replies ? JSON.parse(item.replies) : [], // 解析 replies 字符串
                        likedIps: item.likedIps ? JSON.parse(item.likedIps) : [] // 解析 likedIps 字符串
                    })),
                    total: res.data.total,
                    hasMore: res.data.hasMore
                }
            }
            return res.data
        } else {
            console.error('请求失败:', res.message)
            return Promise.reject(new Error(res.message || '请求失败'))
        }
    },
    (error: any) => {
        console.error('请求错误:', error)
        return Promise.reject(error)
    }
)

interface RequestConfig extends InternalAxiosRequestConfig {
    params?: any
    data?: any
}

const request = {
    get<T = any>(url: string, config?: RequestConfig): Promise<T> {
        // 如果有 params，直接展开到 config 中，而不是嵌套在 params 对象里
        if (config?.params) {
            config = {
                ...config,
                params: {
                    pageNum: config.params.pageNum,
                    pageSize: config.params.pageSize,
                    content: config.params.content,
                    location: config.params.location,
                    startDate: config.params.startDate,
                    endDate: config.params.endDate
                }
            }
        }
        return service.get(url, config)
    },
    post<T = any>(url: string, data?: object, config?: RequestConfig): Promise<T> {
        return service.post(url, data, config)
    },
    put<T = any>(url: string, data?: object, config?: RequestConfig): Promise<T> {
        return service.put(url, data, config)
    },
    delete<T = any>(url: string, config?: RequestConfig): Promise<T> {
        return service.delete(url, config)
    }
}

export default request
